package com.lmh.friend.manager;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lmh.common.core.constants.CacheConstants;
import com.lmh.common.core.enums.ResultCode;
import com.lmh.common.redis.service.RedisService;
import com.lmh.common.security.exception.ServiceException;
import com.lmh.friend.domain.question.Question;
import com.lmh.friend.domain.question.vo.QuestionVO;
import com.lmh.friend.mapper.question.QuestionMapper;
import com.lmh.friend.mapper.user.UserSubmitMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class QuestionCacheManager {
    @Autowired
    private RedisService redisService;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private UserSubmitMapper userSubmitMapper;

    public Long getListSize() {
        return redisService.getListSize(CacheConstants.QUESTION_LIST);
    }

    public void refreshCache() {
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>()
                .select(Question::getQuestionId)
                .orderByDesc(Question::getCreateTime));
        if (CollectionUtil.isEmpty(questionList)) {
            return;
        }
        List<Long> questionIdList = questionList.stream().map(Question::getQuestionId).collect(Collectors.toList());
        redisService.rightPushAll(CacheConstants.QUESTION_LIST,questionIdList);
    }

    public Long preQuestion(Long questionId) {
        // 先找到当前题目对应的索引
        Long index = redisService.indexOfForList(CacheConstants.QUESTION_LIST,questionId);
        // 如果题目是第一题的话就不允许跳转到上一题
        if (index == 0) {
            throw new ServiceException(ResultCode.FAILED_FIRST_QUESTION);
        }
        return redisService.indexForList(CacheConstants.QUESTION_LIST,index - 1,Long.class);
    }

    public Long nextQuestion(Long questionId) {
        // 先找到当前题目对应的索引
        Long index = redisService.indexOfForList(CacheConstants.QUESTION_LIST,questionId);
        Long lastIndex = redisService.getListSize(CacheConstants.QUESTION_LIST);
        // 如果题目是最后一题的话就不允许跳转到下一题
        if (index == lastIndex - 1) {
            throw new ServiceException(ResultCode.FAILED_LAST_QUESTION);
        }
        return redisService.indexForList(CacheConstants.QUESTION_LIST,index + 1,Long.class);
    }

    public List<Long> getHotQutsionList() {
        return redisService.getCacheListByRange(CacheConstants.QUESTION_HOST_LIST
                ,0,10, Long.class);
    }

    public List<Long> refreshHotQuestionList() {
        List<Long> questionIdList = userSubmitMapper.selectHostQuestionList();
        redisService.rightPushAll(CacheConstants.QUESTION_HOST_LIST,questionIdList);
        return questionIdList;
    }
}
